<?php
require_once("PHPMailer/class.phpmailer.php");

/**
 * <code>
 *
 *  $file  = file("/home/zeka/documents/emails_01_06.csv");
 *
 *
 *  $mailer = new ZekaMailer(
 *      $subject,
 *      $body,
 *      'exemple@mail.de',
 *      'password',
 *      $from=null,
 *      $fromName
 *  );
 *
 *  $mailer->setHost( $host );
 *
 *  $mailer->setPort( $port );
 *
 *  $mailer->addEmail( $file );
 *  $mailer->addEmail( 'eb@bilink.ua' );
 *  $mailer->addEmail( 'seleznov.igor@gmail.com' );
 *
 *  $mailer->addBcc( 'eb@bilink.ua' );
 *
 *  $mailer->setReplyTo( 'dealer@rodina.tv' );
 *
 *
 *  $mailer->addAttach( '/home/zeka/documents/1_dileri_flaer_50off_1.png' );
 *  $mailer->addAttach( '/home/zeka/documents/1_dileri_flaer_50off_2.png' );
 *
 *  $mailer->sendMess(true);
 *
 *  echo $mailer->printNotif();
 *
 *
 *  unset( $mailer );
 *
 * </code>
 */
class ZekaMailer
{
    /**
     * @var PHPMailer $mail
     */
    protected $mail;

    /**
     * @var string $host
     */
    protected $host;
    
    /**
     * @var integer $port
     */
    protected $port;
    
    /**
     * @var string $username
     */
    protected $username;
    
    /**
     * @var string $password
     */
    protected $password;
    
    /**
     * @var string $replyTo
     */
    protected $replyTo;
    
    /**
     * @var array $emails
     */
    protected $emails=array();
    
    /**
     * @var array $bcc
     */
    protected $bcc=array();
    
    /**
     * @var array $attachments
     */
    protected $attachments=array();
    
    /**
     * @var string $from
     */
    protected $from;
    
    
    /**
     * @var string $fromName
     */
    protected $fromName;
    
    
    /**
     * @var string $subject
     */
    protected $subject;
    
    /**
     * @var string $body
     */
    protected $body;
    
    /**
     * @var boolean $isHTML
     */
    protected $isHTML=true;

    /**
     * @var array $notifications
     */
    public $notifications=array('notif' => array(),'warning' => array(),'critical' => array());
    
    /**
     * @var integer $sleep
     */
    protected $sleep=5;

    
    public function __construct(
        $subject,
        $body,
        $username,
        $password,
        $from=null,
        $fromName=null
    )
    {
        $this->mail = new PHPMailer();
        
        $this->username = $username;
        $this->password = $password;
        $this->subject = $subject;
        $this->body = $body;
        $this->from = $from ?: 'Info';
        $this->fromName = $fromName ?: 'Rodina.TV';
    }
    
    /**
     * set Sleep
     */
    public function setSleep( $sleep )
    {
        $this->sleep = $sleep;
        return $this;
    }
    
    /**
     * set isHTML
     */
    public function setIsHTML( $isHTML )
    {
        $this->isHTML = $isHTML;
        return $this;
    }
    
    /**
     * set Host
     */
    public function setHost( $host )
    {
        $this->host = $host;
        return $this;
    }
    
    /**
     * set Port
     */
    public function setPort( $port )
    {
        $this->port = $port;
        return $this;
    }
    
    /**
     * set Port
     */
    public function setReplyTo( $replyTo )
    {
        $this->replyTo = $replyTo;
        return $this;
    }
    
    /**
     * add Email
     */
    protected function isValidEmail( $email )
    {
        if( !filter_var($email, FILTER_VALIDATE_EMAIL) )
#        if(!preg_match('/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i',$email) )
        {
            $this->notifications['warning'][] = sprintf("WARNING: Email %s is not valid",$email);
            return false;
        }
        return true;
    }
    
    /**
     * add Email
     */
    public function addEmail( $emails )
    {
        if( !is_array($emails) ) $emails = array( $emails );
        
        foreach( $emails as $email )
        {
            $email = trim( $email );
            
            if( $this->isValidEmail($email) )
            {
                if( !in_array( $email, $this->emails ) )
                $this->emails[] = $email;
            }
        }
        return $this;
    }
    
    /**
     * add Bcc
     */
    public function addBcc( $emails )
    {
        if( !is_array($emails) ) $emails = array( $emails );
        
        foreach( $emails as $email )
        {
            $email = trim( $email );
            
            if( $this->isValidEmail($email) )
            {
                $this->bcc[] = $email;
            }
        }
        return $this;
    }
    
    /**
     * add Attach
     */
    public function addAttach( $attach )
    {
        if( !file_exists($attach) )
        {
            $this->notifications['critical'][] = sprintf("File %s is not exists",$attach);
        }
        else
        {
            $this->attachments[] = array( $attach, basename($attach) );
        }
        return $this;
    }
    
    /**
     * sendMess
     */
    public function sendMess( $mode=false)
    {
        if( $this->notifications['critical'] ) return false;
        
        $this->mail->IsSMTP();
        $this->mail->Host = $this->host;
        $this->mail->Port = $this->port;
        $this->mail->SMTPAuth = true;
        $this->mail->SMTPSecure = "tls";
        $this->mail->Username = $this->username;
        $this->mail->Password = $this->password;
        $this->mail->Timeout = 10;
        $this->mail->CharSet = 'utf-8';
        $this->mail->IsHTML($this->isHTML);
        $this->mail->SMTPKeepAlive = true;
        $this->mail->From = $this->from;
        $this->mail->FromName = $this->fromName;
        $this->mail->Subject = $this->subject;
        $this->mail->Body = $this->body;
        
        if( $this->replyTo )
        {
            $this->mail->AddReplyTo( $this->replyTo );
        }
        
        if( $this->attachments )
        {
            foreach( $this->attachments as $attach )
            {
                $this->mail->AddAttachment( $attach[0], $attach[1] );
            }
        }
        
        $this->emails = array_unique( $this->emails );
        
        foreach( $this->emails as $email )
        {
            if( $this->notifications['critical'] ) return false;
            
            $this->mail->AddAddress( $email );
            
            if( $this->bcc )
            {
                foreach( $this->bcc as $bcc )
                {
                    $this->mail->AddBcc( $bcc );
                }
            }
            if( $mode )
            {
                if( $this->mail->Send() )
                {
                    $this->mail->ClearAllRecipients();
                    $this->notifications['notif'][] = sprintf( "%s -- Send OK", $email );
                }
                else
                {
                    $this->notifications['critical'][] = $this->mail->ErrorInfo;
                }
            }
            else
            {
                $this->notifications['notif'][] = sprintf( "__MODE__ %s -- Send OK", $email );
            }
            sleep( $this->sleep );
        }
        return true;
    }
    
    /**
     * printNotif
     */
    public function printNotif()
    {
        $mess = '';
        if( $this->notifications['critical'] )
        {
            $mess .= implode( "\n", $this->notifications['critical'] );
            $mess .= "\n";
        }
        if( $this->notifications['warning'] )
        {
            $mess .= implode( "\n", $this->notifications['warning'] );
            $mess .= "\n";
        }
        if( $this->notifications['notif'] )
        {
            $mess .= implode( "\n", $this->notifications['notif'] );
            $mess .= "\n";
        }
        return $mess ?: "EMPTY\n";
    }
    
    
}